const { request, clearAuth } = require('../../utils/request');
const pageBehavior = require('../../utils/pageBehavior');
const { smartNavigate } = require('../../utils/navigation');

Page({
  behaviors: [pageBehavior],

  data: {
    name: '',
    idCard: '',
    loading: false,
    errorMessage: ''
  },

  onNameInput(e) {
    this.setData({ name: e.detail?.value || '' });
  },

  onIdInput(e) {
    this.setData({ idCard: e.detail?.value || '' });
  },

  async handleVerify() {
    if (this.data.loading) return;
    const { name, idCard } = this.data;
    if (!name) {
      this.showError('请输入真实姓名');
      return;
    }
    if (!idCard) {
      this.showError('请输入身份证号码');
      return;
    }
    const idCardOk = /(^\d{15}$)|(^\d{17}[0-9Xx]$)/.test(idCard);
    if (!idCardOk) {
      this.showError('身份证号码格式不正确');
      return;
    }
    this.setData({ loading: true, errorMessage: '' });
    try {
      const res = await request({
        url: '/api/miniapp/auth/identityVerify',
        method: 'POST',
        data: { name, idCard },
        showErrorToast: false
      });
      if ((res?.code || 200) !== 200) {
        throw new Error(res?.message || '认证失败');
      }
      this.showSuccess('认证成功，正在跳转');
      setTimeout(() => {
        smartNavigate('/pages/index/index');
      }, 500);
    } catch (err) {
      this.setData({ errorMessage: err?.message || '认证失败' });
      this.showError(this.data.errorMessage);
    } finally {
      this.setData({ loading: false });
    }
  },

  handleSkip() {
    wx.showToast({ title: '已进入游客模式', icon: 'none' });
    setTimeout(() => {
      smartNavigate('/pages/index/index');
    }, 300);
  }
});


